<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2007/07/10 08:57:50 $)
// $RCSfile: functions_clientkb.php,v $ : $Revision: 1.13 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Build the nav link
*/
function buildNavLink($nav)
{
	global $dbCore, $CONF;

	$categorybits = explode(",", $nav);
	if (!count($categorybits))
	{
		return;
	}

	$_categoryidlist = array();
	foreach ($categorybits as $key=>$val)
	{
		if (is_numeric($val) && !empty($val))
		{
			$_categoryidlist[] = intval($val);
		}
	}

	$_categorylist = array();
	$dbCore->query("SELECT `kbcategoryid`, `title` FROM `". TABLE_PREFIX ."kbcategories` WHERE `kbcategoryid` IN (". buildIN($_categoryidlist) .");");
	while ($dbCore->nextRecord())
	{
		$_categorylist[$dbCore->Record["kbcategoryid"]] = $dbCore->Record["title"];
	}

	$_nav = "";
	$navbits = "0";
	foreach ($_categoryidlist as $key=>$val)
	{
		if (defined("ISMODERNBILLV5"))
		{
			$_nav .= ' &raquo; <a href="'. 'faqs.php?action='. getActionID("ShowFAQs") .'&sid='. $CONF["user"]["sessionID"] .'&_m=knowledgebase&_a=view&parentcategoryid='. intval($val) .'&nav='. urlencode($navbits) .'" id="navlink">'.$_categorylist[$val]."</a>";
		} else {
			$_nav .= ' &raquo; <a href="'. iif(defined("ISMODERNBILL"), 'user.php?op=menu&tile=faq&_m=knowledgebase&_a=view&parentcategoryid='. intval($val) .'&nav='. urlencode($navbits), 'index.php?_m=knowledgebase&_a=view&parentcategoryid='. intval($val) .'&nav='. urlencode($navbits)) .'" id="navlink">'.$_categorylist[$val]."</a>";
		}
		$navbits .= ",".intval($val);
	}

	return $_nav;
}

/**
* Gets a list of sub categories from the parent category
*/
function getSubCategories($kbcategoryid, $isrss = false)
{
	global $dbCore, $_SWIFT;

	$categorylist = $categoryidlist = $splitcatlist = array();
	$index = $splitindex = 0;
	if ($_SWIFT["settings"]["kb_catdisplayorder"] == 4)
	{
		$orderfield = "totalarticles";
	} else if ($_SWIFT["settings"]["kb_catdisplayorder"] == 3) {
		$orderfield = "kbcategoryid";
	} else if ($_SWIFT["settings"]["kb_catdisplayorder"] == 2) {
		$orderfield = "title";
	} else {
		$orderfield = "displayorder";
	}

	if ($_SWIFT["settings"]["kb_catorder"] == 2)
	{
		$ordertype = "DESC";
	} else {
		$ordertype = "ASC";
	}


	$dbCore->query("SELECT kbcategories.* FROM `". TABLE_PREFIX ."kbcategories` AS kbcategories LEFT JOIN `". TABLE_PREFIX ."tgroupassigns` AS tgroupassigns ON (kbcategories.kbcategoryid = tgroupassigns.toassignid AND tgroupassigns.type = '". TGROUP_KNOWLEDGEBASE ."') WHERE tgroupassigns.tgroupid = '". intval($_SWIFT["tgroup"]["tgroupid"]) ."' AND kbcategories.parentcategoryid = '". intval($kbcategoryid) ."' ORDER BY ". $dbCore->escape($orderfield) ." ". $dbCore->escape($ordertype) .";");
	while ($dbCore->nextRecord())
	{
		// Add only if the sub cat belongs to this user group
		if ($dbCore->Record["categorytype"] == SWIFTPUBLIC)
		{
			$catmod = $index%2;
			$categoryidlist[] = $dbCore->Record["kbcategoryid"];
			$categorylist[$dbCore->Record["kbcategoryid"]] = $dbCore->Record;
			$categorylist[$dbCore->Record["kbcategoryid"]]["split"] = $catmod;
			$categorylist[$dbCore->Record["kbcategoryid"]]["articlelist"] = $categorylist[$dbCore->Record["kbcategoryid"]]["articleidlist"] = array();
			$lastitem = $dbCore->Record["kbcategoryid"];

			if ($catmod == 0)
			{
				$splitcatlist[$splitindex][1] = &$categorylist[$dbCore->Record["kbcategoryid"]];
			} else if ($catmod == 1) {
				$splitcatlist[$splitindex][2] = &$categorylist[$dbCore->Record["kbcategoryid"]];
				$splitindex++;
			}
			$index++;
		}
	}

	if (isset($lastitem))
	{
		$categorylist[$lastitem]["split"] = 1;
	}
	unset($lastitem);

	// Add the parent category to the category list too
	$categoryidlist[] = $kbcategoryid;

	// Once we have the list of categories under the parent category we itterate through the links and get all the articles under the specified categories
	if ($_SWIFT["settings"]["kb_ardisplayorder"] == 6)
	{
		$orderfield = "articlerating";
	} else if ($_SWIFT["settings"]["kb_ardisplayorder"] == 5) {
		$orderfield = "views";
	} else if ($_SWIFT["settings"]["kb_ardisplayorder"] == 4) {
		$orderfield = "editeddateline";
	} else if ($_SWIFT["settings"]["kb_ardisplayorder"] == 3) {
		$orderfield = "kbarticleid";
	} else if ($_SWIFT["settings"]["kb_ardisplayorder"] == 2) {
		$orderfield = "subject";
	} else {
		$orderfield = "displayorder";
	}

	if ($_SWIFT["settings"]["kb_arorder"] == 2)
	{
		$ordertype = "DESC";
	} else {
		$ordertype = "ASC";
	}

	$tmpkbcatarticlelist = $kbcatarticlelist = $kbarticlelist = $catcountlist = $kbarticleidlist = $parentkbarticlelist = $parentkbarticleidlist = array();
	$dbCore->query("SELECT kbarticlelinks.kbcategoryid, kbarticlelinks.kbarticleid FROM `". TABLE_PREFIX ."kbarticlelinks` AS kbarticlelinks LEFT JOIN `". TABLE_PREFIX ."kbarticles` AS kbarticles ON (kbarticlelinks.kbarticleid = kbarticles.kbarticleid) WHERE kbarticlelinks.kbcategoryid IN (". buildIN($categoryidlist) .") ORDER BY kbarticles.". $dbCore->escape($orderfield) ." ". $dbCore->escape($ordertype) .";");
	while ($dbCore->nextRecord())
	{
		$tmpkbcatarticlelist[$dbCore->Record["kbcategoryid"]][] = $dbCore->Record["kbarticleid"];
	}

	// Ok by now we should have had the entire list of categories, what we need is to limit the article fetching under categories to a specific number in settings to avoid high load.
	$articlelimit = $_SWIFT["settings"]["kb_maxcatarticles"];
	foreach ($tmpkbcatarticlelist as $key=>$val)
	{
		if (is_array($val))
		{
			foreach ($val as $dkey=>$dval)
			{
				if (($catcountlist[$key] >= $articlelimit && $key != $kbcategoryid) || ($articlelimit == 0 && $key != $kbcategoryid))
				{
					continue;
				}

				// Perfecto, Now see if this article belongs to the parent category, if yes, fill up a seperate array for this.
				if ($key == $kbcategoryid)
				{
					$parentkbarticleidlist[] = $dval;
					$kbarticleidlist[] = $dval;
				} else {
					$kbcatarticlelist[$key][] = $dval;
					$kbarticleidlist[] = $dval;
					$categorylist[$key]["articleidlist"][] = $dval;
					if (empty($catcountlist[$key]))
					{
						$catcountlist[$key] = 0;
					}
					$catcountlist[$key]++;
				}
			}
		}
	}

	// Great, now that we have the list of articles to fetch we fetch the article data completely
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbarticles` AS kbarticles LEFT JOIN `". TABLE_PREFIX ."kbarticledata` AS kbarticledata ON (kbarticles.kbarticleid = kbarticledata.kbarticleid) WHERE kbarticles.kbarticleid IN (". buildIN($kbarticleidlist) .");");
	while ($dbCore->nextRecord())
	{
		if ($dbCore->Record["articlestatus"] == ARTICLE_PUBLISHED) // Make sure we only display the published articles
		{
			$kbarticlelist[$dbCore->Record["kbarticleid"]] = $dbCore->Record;
			if ($isrss == true)
			{
				$kbarticlelist[$dbCore->Record["kbarticleid"]]["contents"] = substr($dbCore->Record["contents"], 0, $_SWIFT["settings"]["kb_rssclimit"]);
			} else {
				$kbarticlelist[$dbCore->Record["kbarticleid"]]["contents"] = strip_tags(substr($dbCore->Record["contents"], 0, $_SWIFT["settings"]["kb_climit"]));
			}
		}
	}

	// Loop again to fill the category list
	foreach ($categorylist as $key=>$val)
	{
		foreach ($val["articleidlist"] as $akey=>$aval)
		{
			if (!empty($kbarticlelist[$aval]["kbarticleid"]))
			{
				$categorylist[$key]["articlelist"][] = $kbarticlelist[$aval];
			}
		}
		$categorylist[$key]["articlecount"] = count($categorylist[$key]["articlelist"]);
	}

	foreach ($parentkbarticleidlist as $key=>$val)
	{
		if (!empty($kbarticlelist[$val]["kbarticleid"]))
		{
			$parentkbarticlelist[] = $kbarticlelist[$val];
		}
	}

	$funcresult = array();
	$funcresult["categorylist"] = $categorylist;
	$funcresult["kbarticlelist"] = $kbarticlelist;
	$funcresult["parentkbarticlelist"] = $parentkbarticlelist;
	$funcresult["splitcatlist"] = $splitcatlist;

	return $funcresult;
}

/**
* Check the category against the current user group
*/
function checkCatTemplateGroup($kbcategoryid)
{
	global $_SWIFT, $dbCore;

	// Always return true if its the main category
	if ($kbcategoryid == 0)
	{
		return true;
	}

	$_kbcategory = $dbCore->queryFetch("SELECT kbcategories.kbcategoryid FROM `". TABLE_PREFIX ."kbcategories` AS kbcategories LEFT JOIN `". TABLE_PREFIX ."tgroupassigns` AS tgroupassigns ON (kbcategories.kbcategoryid = tgroupassigns.toassignid AND tgroupassigns.type = '". TGROUP_KNOWLEDGEBASE ."') WHERE tgroupassigns.tgroupid = '". intval($_SWIFT["tgroup"]["tgroupid"]) ."' AND kbcategories.kbcategoryid = '". intval($kbcategoryid) ."' LIMIT 1;");
	if (!empty($_kbcategory["kbcategoryid"]))
	{
		return true;
	}

	return false;
}

/**
* Update the article rating
*/
function updateArticleRating($kbarticleid, $ratetype)
{
	global $dbCore, $_SWIFT;

	$_article = getArticle($kbarticleid);
	if (!$_article)
	{
		return false;
	}

	$_article["ratinghits"]++;
	if ($ratetype == true)
	{
		$_article["ratingcount"] += 5;
	}

	if ($_article["ratinghits"] == 0) {
		$_rating = "0";
	} else {
		$_rating = $_article["ratingcount"]/$_article["ratinghits"];
	}
	if ($_rating >= 5)
	{
		$_rating = 5;
	}
	$_rating = round($_rating);

	if ($ratetype == true) {
		$dbCore->query("UPDATE `". TABLE_PREFIX ."kbarticles` SET `ratinghits` = `ratinghits`+1, `ratingcount` = `ratingcount`+ 5, `articlerating` = '". intval($_rating) ."' WHERE `kbarticleid` = '". intval($_article["kbarticleid"]) ."';");
	} else {
		$dbCore->query("UPDATE `". TABLE_PREFIX ."kbarticles` SET `ratinghits` = `ratinghits`+1, `articlerating` = '". intval($_rating) ."' WHERE `kbarticleid` = '". intval($_article["kbarticleid"]) ."';");
	}

	return true;
}

/**
* Email an Article
*/
function emailArticle($kbarticleid, $sendername, $fullname, $email)
{
	global $dbCore, $_SWIFT, $template;

	$_article = getArticle($kbarticleid);
	if (!$_article || $_article["articlestatus"] != "published")
	{
		return false;
	}

	$template->setGroup($_SWIFT["tgroup"]["tgroupid"]);

	$template->assign("article", $_article);
	$template->assign("sendername", $sendername);
	$template->assign("fullname", $fullname);
	$template->assign("email", $email);

	$template->assign("contentshtml", getProcessedHTML($contents));
	$template->assign("contentstext", getProcessedText($contents));
	$template->assign("ishtml", true);
	$_templateresulthtml = $template->displayTemplate("email_kbarticle", TEMPLATE_DB);
	$template->assign("ishtml", false);
	$_templateresulttext = $template->displayTemplate("email_kbarticle", TEMPLATE_DB);
	require_once ("./includes/functions_mail.php");
	$mailObj = new SWIFT_Mail();

	$mailObj->setSubject(sprintf($_SWIFT["language"]["emailarticlesubject"], $_article["subject"], $sendername));
	$mailObj->setData($_templateresulthtml, $_templateresulttext);

	$mailObj->sendMail(array($email), $_SWIFT["settings"]["general_returnemail"], $_SWIFT["settings"]["general_companyname"], false);
}
?>